<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索内容"
            v-model="canshu.query"
            @keyup.enter.native="getTableList()"
            @keyup.native="getTableList()"
            @clear="getTableList()"
            clearable
          >
            <el-button slot="append" icon="el-icon-search" @click="getTableList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-row>
            <el-button type="primary" @click="adduser = true">添加用户</el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-table :data="tableList" stripe style="width: 100%" border>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="手机号码" width="120"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column label="状态" width="80">
          <el-switch slot-scope="ztDate" v-model="ztDate.row.mg_state" @change=" tai(ztDate.row) "></el-switch>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="btdata">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click=" xiubox(btdata.row.id)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deluser(btdata.row.id)"
            ></el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="peibox(btdata.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="canshu.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="canshu.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tot"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的弹出框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="adduser"
      width="50%"
      @close="$refs.addform.resetFields()"
    >
      <el-form label-width="80px" :model="addcan" ref="addform" :rules="rules" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addcan.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input ref="myword" v-model="addcan.password" show-password>></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addcan.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addcan.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adduser = false">取 消</el-button>
        <el-button type="primary" @click=" addsure()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的弹出框 -->
    <el-dialog title="修改用户" :visible.sync="xiuuser" width="50%" ref="xiuform" @close="reset()">
      <el-form ref="xiuform" label-width="80px" :model="xiucan" :rules="xiurules" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="xiucan.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="xiucan.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="xiucan.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="xiuuser = false">取 消</el-button>
        <el-button type="primary" @click=" xiusure()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户的弹出框 -->
    <el-dialog
      title="用户分配角色"
      :visible.sync="peiuser"
      width="50%"
      ref="peiform"
      @close="$refs.peiform.resetFields()"
    >
      <el-form ref="peiform" label-width="120px" :model="peican" :rules="peirules">
        <el-form-item label="当前的用户:">{{peican.username}}</el-form-item>

        <el-form-item label="当前的角色:">{{peican.role_name}}</el-form-item>
        <el-form-item label="分配新角色:" prop="rid">
          <el-select v-model="peican.rid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="peiuser = false">取 消</el-button>
        <el-button type="primary" @click=" peisure()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var Mob = (rule, value, callback) => {
      var reg = /^1[3-9]\d{9}$/
      if (!reg.test(value)) {
        return callback(new Error('手机格式不正确'))
      } else {
        callback() // 校验没问题继续执行
      }
    }
    return {
      // 分配的
      peiuser: false,
      peican: {
        username: '',
        role_name: '',
        rid: '' // 接收新分配角色
      },
      peirules: {
        rid: [{ required: true, message: '分配角色必填', trigger: 'blur' }]
      },
      // 接收下拉可以分配的信息
      options: [],
      // 修改的
      xiuuser: false,
      xiucan: {
        username: '',
        email: '',
        mobile: ''
      },
      xiurules: {
        mobile: [
          { required: true, message: '手机号码必填', trigger: 'blur' },
          { validator: Mob, trigger: 'blur' }
        ]
      },
      // 添加的
      adduser: false,
      addcan: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 填充分页器里面的total
      tot: 0,
      tableList: [],
      canshu: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      rules: {
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        password: [{ required: true, message: '密码必填', trigger: 'blur' }],
        mobile: [
          { required: true, message: '手机号码必填', trigger: 'blur' },
          { validator: Mob, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'addcan.password': function (newVal, oldVal) {
      // console.log(newVal, oldVal)
      // 1. 给el-input设置ref属性(mypass)，使得当前组件被找到，this.$refs.mypass
      // 2. 通过ref属性找到el-input对应的VueComponent对象并调用getInput()方法找到内部的input框标签
      // console.log(this.$refs.myword)
      // console.log(this.$refs.myword.getInput())
      console.log(newVal.trim().length)

      if (newVal.trim().length <= 8 && newVal.trim().length > 0) {
        this.$refs.myword.getInput().style.border = '1px solid blue'
      } else if (newVal.trim().length === 0) {
        this.$refs.myword.getInput().style.border = '1px solid #DCDFE6'
      } else {
        this.$refs.myword.getInput().style.border = '1px solid red'
      }
    }
  },
  methods: {
    // pei的
    async peibox (Pi) {
      this.peiuser = true
      // console.log(Pi)
      // 把接收过来的参数赋值给data成员里面的peican
      this.peican = Pi

      // 发送请求获得分配新角色的列表
      var { data: dt } = await this.$http.get('roles')
      // console.log(dt)
      // console.log(this.peican.rid)

      // 把获得的数据赋值给options
      this.options = dt.data
    },
    peisure () {
      this.$refs.peiform.validate(async valid => {
        if (valid) {
          var { data: dt } = await this.$http.put(
            'users/' + this.peican.id + '/role',
            { rid: this.peican.rid }
          )
          console.log(dt)
          // 隐藏分配弹出框
          this.peiuser = false
          // 显示添加成功的消息
          this.$message.success(dt.meta.msg)
          // 重新渲染
          this.getTableList()
        }
      })
    },
    // 修改状态
    async tai (Ti) {
      // console.log(Ti)

      var { data: dt } = await this.$http.put(
        'users/' + Ti.id + '/state/' + Ti.mg_state
      )
      console.log(dt)
      this.$message.success(dt.meta.msg)
      this.getTableList()
    },
    // 修改用户
    async xiubox (info) {
      // 显示修改的弹框
      this.xiuuser = true
      // console.log(info)

      var { data: dt } = await this.$http.get('users/' + info)
      // console.log(dt)

      // 把传过来的当面行的数据赋值给修改框参数
      this.xiucan = dt.data
      console.log(this.xiucan)
    },
    // 提交修改的请求
    xiusure () {
      this.$refs.xiuform.validate(async valid => {
        if (valid) {
          console.log(this.xiucan)

          var { data: dt } = await this.$http.put(
            'users/' + this.xiucan.id,
            this.xiucan
          )
          // console.log(dt)
          this.xiuuser = false // 隐藏修改弹框
          // 提示修改成功的消息
          // console.log(this.tableList)

          this.$message.success(dt.meta.msg)

          // 重新渲染
          this.getTableList()
        }
      })
    },
    reset () {
      this.$refs.xiuform.resetFields()
    },
    // 删除用户
    deluser (id) {
      this.$confirm('确定要删除该用户, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          var { data: dt } = await this.$http.delete('users/' + id)
          console.log(dt)
          if (this.canshu.pagenum !== 1 && this.tableList.length === 1) {
            this.canshu.pagenum--
          }
          // 提示添加成功的消息
          this.$message.success(dt.meta.msg)
          // 重新渲染
          this.getTableList()
        })
        .catch(() => {})
    },
    // 添加用户
    addsure () {
      this.$refs.addform.validate(async valid => {
        if (valid) {
          var { data: dt } = await this.$http.post('users', this.addcan)
          console.log(dt)
          // 隐藏弹框
          this.adduser = false
          // 提示添加成功的消息
          this.$message.success(dt.meta.msg)
          // 重新渲染
          this.getTableList()
        }
      })
    },

    handleSizeChange (newsize) {
      // newsize 表示选择当前页面显示几条数据
      // console.log(newsize)
      this.canshu.pagesize = newsize
      this.getTableList()
    },
    handleCurrentChange (newpage) {
      // newpage 表示的是当前的页面
      // console.log(newpage)
      this.canshu.pagenum = newpage
      this.getTableList()
    },
    // 一进页面渲染数据
    async getTableList () {
      var { data: dt } = await this.$http.get('users', { params: this.canshu })
      // if (dt.meta.status !== 200) {
      //   return this.$message.error(dt.meta.msg)
      // }
      // console.log(dt)
      // 把获得的数据列表赋值给tableList
      this.tableList = dt.data.users
      // 把获得的总条数赋值给分页器
      this.tot = dt.data.total
    }
  },
  created () {
    this.getTableList()
  }
}
</script>

<style lang="less" scoped>
</style>
